package com.clkj.zhonghui.service.topic;

import com.clkj.zhonghui.dao.topic.TopicCommentMapper;
import com.clkj.zhonghui.dao.topic.TopicMapper;
import com.clkj.zhonghui.dao.topic.TopicPriseMapper;
import com.clkj.zhonghui.pojo.common.ExcelRead;
import com.clkj.zhonghui.pojo.common.OSSUtil;
import com.clkj.zhonghui.pojo.common.UploadFile;
import com.clkj.zhonghui.pojo.product.Product;
import com.clkj.zhonghui.pojo.stored.UserStored;
import com.clkj.zhonghui.pojo.topic.Topic;
import com.clkj.zhonghui.pojo.topic.TopicComment;
import com.clkj.zhonghui.pojo.topic.TopicPrise;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @Author：周佳润
 * @Date：2024/7/16 上午9:27
 */
@Service
public class TopicServiceImpl implements TopicService {

    @Resource
    private TopicMapper topicMapper;

    @Resource
    private TopicCommentMapper topicCommentMapper;

    @Resource
    private TopicPriseMapper topicPriseMapper;


    @Override
    public PageInfo getTopicPage(String topicTitle, Integer topicFlag, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Example example = new Example(Topic.class);
        Example.Criteria criteria = example.createCriteria();
        if(topicFlag != null){
            criteria.andEqualTo("topicFlag", topicFlag);
        }
        if(topicTitle!= null&& !topicTitle.equals("")){
            criteria.andLike("topicTitle", topicTitle);
        }
        example.orderBy("topicId").desc();
        return new PageInfo(topicMapper.selectByExample(example));
    }

    @Override
    public void addTopic(Topic topic, HttpServletRequest request,String flag) {
        MultipartFile topicfile = ((MultipartRequest) request).getFile("topic");
        MultipartFile topicCoverfile = ((MultipartRequest) request).getFile("topicCoverpic");
        if(topicfile!= null){
            String topicPic = OSSUtil.uploadingImg(topicfile, "zhonghui/topic");
            topic.setTopicCover(topicPic);
        }
        if(topicCoverfile!= null){
            String topicCoverpic = OSSUtil.uploadingImg(topicCoverfile, "zhonghui/topicCoverpic");
            topic.setTopicContent(topicCoverpic);
        }
        if(topicCoverfile!= null) {
            String type = topicCoverfile.getContentType().split("/")[0];
            if (type.equals("video")) {
                topic.setTopicFlag(1);//1为视频
            } else {
                topic.setTopicFlag(0);//0文章
            }
        }
        topic.setTopicStatus(1);
        if("add".equals(flag)){
            topicMapper.insertSelective(topic);
        }else{
            topicMapper.updateByPrimaryKeySelective(topic);
        }
    }

    @Override
    public void updateTopic(String ids, Integer topicStatus) {
        List<Integer> idList = new ArrayList<>();
        String [] id = ids.split(",");
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }
        Example example = new Example(Topic.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("topicId",idList);
        Topic topic = new Topic();
        topic.setTopicStatus(topicStatus);
        topicMapper.updateByExampleSelective(topic,example);
    }

    @Override
    public void delTopic(String ids) {
        List<Integer>idList = new ArrayList<>();
        String [] id = ids.split(",");
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }
        Example example = new Example(Topic.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("topicId",idList);
        topicMapper.deleteByExample(example);
    }

    @Override
    public PageInfo getTopicComment(Integer commentFlag, Integer topicId,Integer pageNumber, Integer pageSize) {
        return new PageInfo(topicCommentMapper.selectTopicComment(commentFlag,topicId));
    }

    @Override
    public void delComment(String ids) {
        List<Integer> idList = new ArrayList<>();
        String [] id = ids.split(",");
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }

        Example example = new Example(TopicComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("commentId",idList);
        topicCommentMapper.deleteByExample(example);
    }

    @Override
    public void addComment(TopicComment topicComment, String flag) {
        if("add".equals(flag)){
            topicCommentMapper.insertSelective(topicComment);
        }else{
            topicCommentMapper.updateByPrimaryKeySelective(topicComment);
        }
    }

    @Override
    public Topic getTopicById(Integer topicId) {
        Example example= new Example(Topic.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("topicId",topicId);
        return topicMapper.selectOneByExample(example);
    }

    @Override
    public void addTopicPrise(TopicPrise topicPrise) {
        Example example= new Example(TopicPrise.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("topicId",topicPrise.getTopicId());
        criteria.andEqualTo("userId",topicPrise.getUserId());
        List<TopicPrise> topicList = topicPriseMapper.selectByExample(example);
        if(topicList.size()>0){
            topicPriseMapper.deleteByExample(example);
        }else{
            topicPriseMapper.insertSelective(topicPrise);
        }
    }

    @Override
    public void listTopicPrise(Integer topicId) {
        topicPriseMapper.selectTopicPrise(topicId);
    }

    @Override
    public void zhidingComment(String ids, Integer topping) {
        List<Integer>  idList = new ArrayList<>();
        String [] id = ids.split(",");
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }
        Example example = new Example(TopicComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("commentId",idList);
        TopicComment comment = new TopicComment();
        comment.setTopping(topping);
        topicCommentMapper.updateByExampleSelective(comment,example);
    }

    @Override
    public void importComment(HttpServletRequest request) {
        {
            try {
                //初始化MAP变量为null
                Map map = null;
                //从请求请求中获取上传文件
                MultipartFile file = ((MultipartRequest) request).getFile("file");
                //将MultipartFile转化为File对象
                File excelFile = UploadFile.multipartFileToFile(file);
                //读取Excel文件返回一个包含Map的List，每个Map代表一行数据
                List<Map<String, Object>> result = ExcelRead.ReadExcelByRC(excelFile, file.getContentType(), 2, -1, false);
                // 初始化一个新的HashMap
                map = new HashMap();
                // 初始化Comment对象和计数器
                TopicComment comment = null;
                List<TopicComment> commentList = new ArrayList<>();
                int num = 0;
                int batchSize = 100; // 每批次插入的数据量
                int batchCount = (result.size() + batchSize - 1) / batchSize; // 计算需要插入的批次数
                //遍历每个批次
                for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) {
                    //计算当前批次的起和结束索引。
                    int startIndex = batchIndex * batchSize;
                    int endIndex = Math.min(startIndex + batchSize, result.size());
                    for (int i = startIndex; i < endIndex; i++) {
                        if (result.get(i).get("1") == null || result.get(i).get("1").equals("null")) {
                            break;
                        }
                        num++;
                        comment = new TopicComment();
                        comment.setCommentContent(result.get(i).get("1").toString());
                        comment.setCommentDate(result.get(i).get("2").toString());
                        comment.setUserId(Integer.parseInt(result.get(i).get("3").toString()));
                        comment.setCommentFlag(Integer.parseInt(result.get(i).get("4").toString()));
                        comment.setParentId(Integer.parseInt(result.get(i).get("5").toString()));
                        comment.setTopping(Integer.parseInt(result.get(i).get("6").toString()));
                        comment.setTopicId(Integer.parseInt(result.get(i).get("7").toString()));
                        commentList.add(comment);
                    }
                    // 批量插入数据
                    if (!commentList.isEmpty()) {
                        topicCommentMapper.insertList(commentList);
                        commentList.clear(); // 清空列表以便下一次插入
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Map getAppTopic(Integer topicId, Integer userId) {
        Map map = new HashMap();
        Example example = new Example(TopicPrise.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("topicId", topicId);
        List<TopicPrise> topicList = topicPriseMapper.selectByExample(example);
        //添加查询TopicPrise中字段topicId的数据
        example = new Example(TopicPrise.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("topicId", topicId);
        List<TopicPrise> countList = topicPriseMapper.selectByExample(example);

        example = new Example(Topic.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("topicId",topicId);
        Topic topic = topicMapper.selectOneByExample(example);
        //点赞数
        if(countList.size()>0){
            topic.setPriseCount(countList.size());
        }else {
            topic.setPriseCount(0);
        }
        //是否点赞
        if(topicList.size()>0){
            topic.setPriseStatus(1);
        }else{
            topic.setPriseStatus(0);
        }
        map.put("topic",topic);
        List<TopicComment> commentList = topicCommentMapper.selectCommentByUser(topicId);
        map.put("topicComment",commentList);
        return map;
    }
}
